package com.fenghuajueli.idiomppp.ui.guessidiom;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.fenghuajueli.idiomppp.adapter.IdiomGuessFillTextGridAdapter;
import com.fenghuajueli.idiomppp.adapter.IdiomGuessWordGridAdapter;
import com.fenghuajueli.idiomppp.database.IdiomDaoUtils;
import com.fenghuajueli.idiomppp.databinding.ActivityGuessIdiomBinding;
import com.fenghuajueli.idiomppp.entity.GuessAnswerEntity;
import com.fenghuajueli.idiomppp.entity.GuessIdiomEntity;
import com.fenghuajueli.idiomppp.entity.IdiomPinParentEntity;
import com.fenghuajueli.idiomppp.entity.IdiomShiYiEntity;
import com.fenghuajueli.idiomppp.entity.IdiomXiaoDbEntity;
import com.fenghuajueli.idiomppp.listener.OnGuessListClickListener;
import com.fenghuajueli.idiomppp.ui.idiompin.IdiomSelectPassPresenter;
import com.fenghuajueli.idiomppp.ui.idiompin.IdiomSelectPassView;
import com.fenghuajueli.idiomppp.utils.MmkvKey;
import com.fenghuajueli.libbasecoreui.listener.OnBaseClick;
import com.fenghuajueli.libbasecoreui.listener.OnListClickListener;
import com.fenghuajueli.libbasecoreui.mvp.LifecycleBaseActivity;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.fenghuajueli.module_route.UserModuleRoute;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
 
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 看图猜成语游戏界面
 */
public class GuessIdiomActivity extends LifecycleBaseActivity<IdiomSelectPassPresenter> implements IdiomSelectPassView {


    GridView bottomFillTextGridView;
    ConstraintLayout containerView;
    LinearLayout idiomShiYiContainer;
    TextView idiomName;
    TextView idiomShiyi;
    TextView tvRiddle;
    TextView tvAnswer;
    TextView tvGuanka;
    ImageView ivIdiomImg;
    ImageView ivBack;
    GridView fillWordGridView;

    String type;

    int currentGuankaNo = -1;

    CompositeDisposable compositeDisposable = new CompositeDisposable();
    private AlertDialog.Builder builder;
    IdiomGuessFillTextGridAdapter idiomGuessFillTextGridAdapter;
    IdiomGuessWordGridAdapter idiomGuessWordGridAdapter;
    GuessIdiomEntity guessIdiomEntity;
    private List<GuessAnswerEntity> guessAnswerEntityList;
    private List<GuessIdiomEntity> guessIdiomEntityList = new ArrayList<>();
    private boolean isButtonEnabled = false;

    private ActivityGuessIdiomBinding binding;

    private void initview() {
        bottomFillTextGridView = binding.bottomFillTextGridView;
        containerView = binding.containerView;
        idiomShiYiContainer = binding.idiomShiYiContainer;
        idiomName = binding.idiomName;
        idiomShiyi = binding.idiomShiyi;
        tvRiddle = binding.tvRiddle;
        tvAnswer = binding.tvAnswer;
        tvGuanka = binding.tvGuanka;
        ivIdiomImg = binding.ivIdiomImg;
        ivBack = binding.ivBack;
        fillWordGridView = binding.fillWordGridView;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityGuessIdiomBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initview();
        ARouter.getInstance().inject(this);
        MyStatusBarUtils.setStatusBarWhite(this, "#00000000");
        tvGuanka.setText("关卡" + (currentGuankaNo + 2));
        type = getIntent().getStringExtra("type");
        currentGuankaNo = getIntent().getIntExtra("guankaNo",-1);
        if ("猜字谜".equals(type)) {
            ivIdiomImg.setVisibility(View.GONE);
            tvRiddle.setVisibility(View.VISIBLE);
            presenter.initWordRiddleData();
        } else if ("猜成语".equals(type)) {
            presenter.initGuessIdiomData();
        } else if ("猜谜语".equals(type)) {
            ivIdiomImg.setVisibility(View.GONE);
            tvRiddle.setVisibility(View.VISIBLE);
            presenter.initRiddleData();
        }
    }

    private void init() {
        currentGuankaNo++;
        if (guessIdiomEntityList.size() > 0) {
            guessIdiomEntity = guessIdiomEntityList.get(currentGuankaNo);
        }
        guessAnswerEntityList = new ArrayList<>();
        for (int i = 0; i < guessIdiomEntity.getAnswerWord().size(); i++) {
            guessIdiomEntity.getAnswerWord().get(i).setSelect(false);
        }
        if ("猜字谜".equals(type)) {
            idiomGuessFillTextGridAdapter = new IdiomGuessFillTextGridAdapter(this, guessIdiomEntity.getAnswerWord(), 1);
        } else if ("猜成语".equals(type)) {
            idiomGuessFillTextGridAdapter = new IdiomGuessFillTextGridAdapter(this, guessIdiomEntity.getAnswerWord(), 4);
        } else if ("猜谜语".equals(type)) {
            idiomGuessFillTextGridAdapter = new IdiomGuessFillTextGridAdapter(this, guessIdiomEntity.getAnswerWord(), 3);
        }

        idiomGuessFillTextGridAdapter.setOnListClickListener(new OnGuessListClickListener<GuessAnswerEntity>() {
            @Override
            public void itemClick(int position, GuessAnswerEntity data, int wordNum) {
                for (int i = 0; i < wordNum; i++) {
                    if (guessAnswerEntityList.get(i).getFillText().isEmpty()) {
                        guessAnswerEntityList.get(i).setFillText(data.getWord());
                        guessAnswerEntityList.get(i).setFill(true);
                        break;
                    }
                }
                idiomGuessWordGridAdapter.notifyDataSetChanged();
            }
        });
        idiomGuessFillTextGridAdapter.setOnBaseClick(new OnBaseClick<String>() {
            @Override
            public void onClick(String s) {
                String answer = "";
                if ("猜字谜".equals(type)) {
                    answer = guessIdiomEntity.getWordAnswer();
                } else if ("猜成语".equals(type)) {
                    answer = guessIdiomEntity.getIdiom();
                } else if ("猜谜语".equals(type)) {
                    answer = guessIdiomEntity.getWordAnswer();
                }

                try {
                    if (answer.equals(s.trim())) {
                        if (MmkvUtils.mmkv.decodeInt(MmkvKey.IdiomGuessPass.name(), 0) <= guessIdiomEntity.getPosition()) {
                            MmkvUtils.mmkv.encode(MmkvKey.IdiomGuessPass.name(), guessIdiomEntity.getPosition() + 1);
                        }
//                        showPassDialog();
                        tvAnswer.setText("下一关");
                        idiomGuessWordGridAdapter.refreshBg(1);
                        if ("猜字谜".equals(type) || "猜谜语".equals(type)) {
                            idiomName.setText(guessIdiomEntity.getWordAnswer());
                            idiomShiyi.setText(guessIdiomEntity.getWordInfo());
                            idiomShiYiContainer.setVisibility(View.VISIBLE);
                            delayHide();
                        } else if ("猜成语".equals(type)) {
                            IdiomShiYiEntity idiomShiYiEntity = IdiomDaoUtils.getIdiomShiYiManager().getOneData(s);
                            if (idiomShiYiEntity != null) {
                                idiomName.setText(idiomShiYiEntity.getIdiom() + "(" + idiomShiYiEntity.getPronounce() + ")");
                                idiomShiyi.setText(idiomShiYiEntity.getExplain());
                                idiomShiYiContainer.setVisibility(View.VISIBLE);
                                delayHide();
                            }
                        }
                    } else {
                        idiomGuessWordGridAdapter.refreshBg(2);
                        showToastMsg("错啦，请再接再厉！");
                        isButtonEnabled = true;
                    }
                } catch (Exception e) {

                }
            }
        });
        if ("猜字谜".equals(type)) {
            guessAnswerEntityList.add(new GuessAnswerEntity(""));
            tvRiddle.setText(guessIdiomEntity.getIdiom());
        } else if ("猜谜语".equals(type)) {
            for (int i = 0; i < 3; i++) {
                guessAnswerEntityList.add(new GuessAnswerEntity(""));
            }
            tvRiddle.setText(guessIdiomEntity.getIdiom());
        } else if ("猜成语".equals(type)) {
            for (int i = 0; i < 4; i++) {
                guessAnswerEntityList.add(new GuessAnswerEntity(""));
            }
            Glide.with(this).load("file:///android_asset/data/image/" + guessIdiomEntity.getImgName()).into(ivIdiomImg);
        }
        bottomFillTextGridView.setAdapter(idiomGuessFillTextGridAdapter);
        idiomGuessWordGridAdapter = new IdiomGuessWordGridAdapter(this, guessAnswerEntityList);
        idiomGuessWordGridAdapter.setOnListClickListener(new OnListClickListener<GuessAnswerEntity>() {
            @Override
            public void itemClick(int position, GuessAnswerEntity data) {
                idiomGuessFillTextGridAdapter.recoveryItem(data.getFillText());
            }
        });
        fillWordGridView.setAdapter(idiomGuessWordGridAdapter);

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GuessBackDialog guessBackDialog = new GuessBackDialog(GuessIdiomActivity.this);
                guessBackDialog.setCancelable(false);
                guessBackDialog.show();
            }
        });

        tvAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("下一关".equals(tvAnswer.getText().toString())) {
                    tvAnswer.setText("查看答案");
                    isButtonEnabled = false;
                    if (guessIdiomEntity.getPosition() + 1 < guessIdiomEntityList.size()) {
                        guessIdiomEntity = guessIdiomEntityList.get(guessIdiomEntity.getPosition() + 1);
                        init();
                    }
                    tvGuanka.setText("关卡" + (currentGuankaNo + 1));
                    MmkvUtils.save(type, currentGuankaNo - 1);
                } else {
                    if (isButtonEnabled) {
                        if ("猜字谜".equals(type) || "猜谜语".equals(type)) {
                            showToastMsg("正确答案是:" + guessIdiomEntity.getWordAnswer());
                        } else if ("猜成语".equals(type)) {
                            showToastMsg("正确答案是:" + guessIdiomEntity.getIdiom());
                        }
                        tvAnswer.setText("下一关");
                    } else {
                        showToastMsg("请先填完后查看答案！");
                    }

                }
            }
        });
    }

    /**
     * 显示通关之后的提示，进入下一关
     */
    private void showPassDialog() {
        String msg = "恭喜通过第" + (guessIdiomEntity.getPosition() + 1) + "关";
        if (MmkvUtils.mmkv.decodeInt(MmkvKey.IdiomGuessPass.name(), 0) <= guessIdiomEntity.getPosition()) {
            MmkvUtils.mmkv.encode(MmkvKey.IdiomGuessPass.name(), guessIdiomEntity.getPosition() + 1);
        }
        builder = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(msg)
                .setNegativeButton("下一关", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        isButtonEnabled = false;
                        if (guessIdiomEntity.getPosition() + 1 < guessIdiomEntityList.size()) {
                            guessIdiomEntity = guessIdiomEntityList.get(guessIdiomEntity.getPosition() + 1);
//                            RuntimeDataUtils.guessIdiomEntity = guessIdiomEntity;
                            init();
                        }
                    }
                }).setNeutralButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.create().show();
    }

    /**
     * 定时隐藏
     */
    private void delayHide() {
        Observable.timer(3, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
            }

            @Override
            public void onNext(Long aLong) {
                idiomShiYiContainer.setVisibility(View.GONE);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void showToastMsg(String msg) {
        ToastUtils.showShort(msg);
    }

    @Override
    public void onBackPressed() {
        GuessBackDialog guessBackDialog = new GuessBackDialog(GuessIdiomActivity.this);
        guessBackDialog.setCancelable(false);
        guessBackDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
        compositeDisposable.clear();
    }

    @Override
    public void loadSuccess(List<IdiomPinParentEntity> idiomPinParentEntityList) {

    }

    @Override
    public void changeBtnUpView(int viewStatus) {

    }

    @Override
    public void changeBtnNextView(int viewStatus) {

    }

    @Override
    public void loadXiaoDataSuccess(List<IdiomXiaoDbEntity> idiomPinParentEntityList) {

    }

    @Override
    public void loadGuessDataSuccess(List<GuessIdiomEntity> idiomPinParentEntityList) {
        guessIdiomEntityList.clear();
        guessIdiomEntityList.addAll(idiomPinParentEntityList);
        init();
    }

    @Override
    public IdiomSelectPassPresenter initPresenter() {
        return new IdiomSelectPassPresenter(this);
    }
}
